package com.xiebishe.mylibrary.common.glide;

import androidx.annotation.NonNull;
import com.bumptech.glide.util.Preconditions;

import com.bumptech.glide.Priority;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.HttpException;
import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.util.ContentLengthInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.Call.Factory;
import okhttp3.Request.Builder;
public class OkHttpStreamFetcher implements DataFetcher<InputStream> {
    private static final String TAG = "OkHttpFetcher";
    private final Factory client;
    private final GlideUrl url;
    private InputStream stream;
    private volatile Call call;

    public OkHttpStreamFetcher(Factory client, GlideUrl url) {
        this.client = client;
        this.url = url;
    }

    public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super InputStream> callback) {
        Builder requestBuilder = (new Builder()).url(this.url.toStringUrl());
        Iterator var4 = this.url.getHeaders().entrySet().iterator();

        while(var4.hasNext()) {
            Map.Entry<String, String> headerEntry = (Map.Entry)var4.next();
            String key = (String)headerEntry.getKey();
            requestBuilder.addHeader(key, (String)headerEntry.getValue());
        }

        Request request = requestBuilder.build();
        this.call = this.client.newCall(request);

        try {
            Response execute = this.call.execute();
            if (execute.isSuccessful()) {
                ResponseBody responseBody = execute.body();
                long contentLength = Preconditions.checkNotNull(responseBody).contentLength();
                this.stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength);
                callback.onDataReady(this.stream);
            } else {
                callback.onLoadFailed(new HttpException(execute.message(), execute.code()));
            }
        } catch (IOException var9) {
            callback.onLoadFailed(var9);
            var9.printStackTrace();
        }

    }

    public void cleanup() {
        try {
            if (this.stream != null) {
                this.stream.close();
            }
        } catch (IOException var2) {
        }

    }

    public void cancel() {
        Call local = this.call;
        if (local != null) {
            local.cancel();
        }

    }

    @NonNull
    public Class<InputStream> getDataClass() {
        return InputStream.class;
    }

    @NonNull
    public DataSource getDataSource() {
        return DataSource.REMOTE;
    }
}

